package com.frinder.base.conf;

import com.frinder.base.global.CODE;
import com.frinder.base.global.Result;
import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName ExpControllerAdvice
 * @Description controller异常处理类
 * @Author frinder
 * @Date 2020/8/6 14:20
 * @Verion 1.0
 */
@Slf4j
@ControllerAdvice
public class ExpControllerAdvice {

    @Order(9)
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result errorHandler(HttpServletRequest request, Exception e) {
        log.error(e.getMessage(), e);
        return Result.result(CODE.FAIL, e.getMessage(), request.getRequestURL().toString());
    }

    @Order(1)
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    @ResponseBody
    public Result validExceptionHandler(MethodArgumentNotValidException ex) {
        List<String> errorList = ex
                .getBindingResult()
                .getFieldErrors()
                .stream()
                .map(e -> String.format("%s:%s", e.getField(), e.getDefaultMessage()))
                .collect(Collectors.toList());
        String message = Joiner.on(";").join(errorList);
        log.error("核验失败：[{}]", message);
        return Result.selfFail(message);
    }
}
